package org.wangzs.blog.common;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

public class LoginFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		Cookie[] cookies = request.getCookies();
		String username = "";
		String password = "";
		for(int i=0;null!=cookies && i<cookies.length;i++){
			if("username".equals(cookies[i].getName())) {
				username = cookies[i].getValue();
			}
			if("password".equals(cookies[i].getName())) {
				password = cookies[i].getValue();
			}
		}
		//匿名用户0,普通登录用户1，管理员2
		int type = 0;
		if("e241138".equals(username) && "BBbb138717".equals(password)){
			type = 2;
		}
		/*String f = request.getRequestURL().append("?")
				.append(request.getQueryString()).toString();*/
		
		if(request.getServletPath().startsWith("/admin") && type != 2){
			response.sendRedirect(request.getContextPath() + "/login");
		}else{
			filterChain.doFilter(request, response);
		}
	}

}
